package com.ruoyi.energy.utils;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.BeanProperty;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.ContextualSerializer;
import com.ruoyi.energy.aop.DoubleFormat;

import java.io.IOException;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.util.Objects;

public class DoubleSerializer extends JsonSerializer<Double> implements ContextualSerializer {

    private String pattern;

    public DoubleSerializer(){

    }

    public DoubleSerializer(String pattern){
        this.pattern = pattern;
    }

    @Override
    public void serialize(Double value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
        if(!Objects.isNull(value)) {
            DecimalFormat df = new DecimalFormat(pattern);
            df.setRoundingMode(RoundingMode.HALF_UP);
            gen.writeString(df.format(value));
        }else {
            gen.writeString("");
        }
    }

    @Override
    public JsonSerializer<?> createContextual(SerializerProvider serializerProvider, BeanProperty beanProperty) throws JsonMappingException {
        if (beanProperty != null) {
            if (Objects.equals(beanProperty.getType().getRawClass(), double.class) || Objects.equals(beanProperty.getType().getRawClass(), Double.class)) {
                DoubleFormat format = beanProperty.getAnnotation(DoubleFormat.class);
                if (format == null) {
                    format = beanProperty.getContextAnnotation(DoubleFormat.class);
                }
                if (format != null) {
                    return new DoubleSerializer(format.pattern());
                }
            }
            return serializerProvider.findValueSerializer(beanProperty.getType(), beanProperty);
        }
        return serializerProvider.findNullValueSerializer(beanProperty);
    }
}
